package com.resou.reader.reader.p;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.arch.lifecycle.LifecycleOwner;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.resou.reader.ACache;
import com.resou.reader.R;
import com.resou.reader.ReSouApplication;
import com.resou.reader.activity.friendboost.FriendBoostActivity;
import com.resou.reader.api.ApiImp;
import com.resou.reader.api.entry.BookContentBean;
import com.resou.reader.api.entry.BookContentData;
import com.resou.reader.api.entry.BookDetailBean;
import com.resou.reader.api.entry.ChapterDataBean;
import com.resou.reader.api.entry.ChapterItemBean;
import com.resou.reader.api.entry.CommonData;
import com.resou.reader.api.entry.LoginData;
import com.resou.reader.api.entry.PayResultBean;
import com.resou.reader.api.entry.Result;
import com.resou.reader.api.entry.ShareTimeBean;
import com.resou.reader.api.entry.SubSidyDetailBean;
import com.resou.reader.api.entry.UserInfoBean;
import com.resou.reader.api.service.BookService;
import com.resou.reader.api.service.PayService;
import com.resou.reader.api.service.SubSidyService;
import com.resou.reader.api.service.UserService;
import com.resou.reader.base.m.IModel;
import com.resou.reader.base.p.BasePresenter;
import com.resou.reader.base.v.BaseActivity;
import com.resou.reader.bookdetail.BookDetailActivity;
import com.resou.reader.bookdetail.comment.CommentListActivity;
import com.resou.reader.bookshelf.readhistory.datasupport.BookCollection;
import com.resou.reader.bookshelf.readhistory.datasupport.DataSupport;
import com.resou.reader.bookshelf.readhistory.datasupport.ReaderHistory;
import com.resou.reader.commom.Constant;
import com.resou.reader.data.bookshelf.BookshelfRepository;
import com.resou.reader.data.bookshelf.BookshelfService;
import com.resou.reader.data.local.LitePalHelper;
import com.resou.reader.dialog.DialogManager;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.mine.login.LoginFragment;
import com.resou.reader.mine.paycenter.PayCenterActivity;
import com.resou.reader.mine.vipcenter.vipCenter.VipCenter;
import com.resou.reader.paycenter.BatchPayActivity;
import com.resou.reader.reader.manager.PageFactory;
import com.resou.reader.reader.manager.ReaderManager;
import com.resou.reader.reader.v.IReaderView;
import com.resou.reader.utils.CacheUtils;
import com.resou.reader.utils.DateUtil;
import com.resou.reader.utils.DeviceUtils;
import com.resou.reader.utils.NetworkUtils;
import com.resou.reader.utils.PreferenceUtil;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.WXUtils;
import com.resou.reader.utils.eventbus.LoadBookEvent;
import com.resou.reader.utils.log.DLog;
import com.resou.reader.view.Loading;
import com.resouxs.free_book.api.FBookFactory;
import com.resouxs.free_book.api.FBookType;
import com.resouxs.free_book.api.IFBook;
import com.resouxs.free_book.api.ZsChapterCallback;
import com.resouxs.free_book.api.ZsFBookCallback;
import com.resouxs.free_book.service.ZsBookChapter;
import com.resouxs.free_book.service.ZsBookChapterContent;
import com.resouxs.free_book.service.ZsChapter;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.umeng.socialize.shareboard.SnsPlatform;

import org.greenrobot.eventbus.EventBus;
import org.litepal.LitePal;

import java.io.File;

import java.lang.ref.WeakReference;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

import static com.resou.reader.commom.Constant.START_MULTI_PAY_REQUEST_CODE;

/**
 * Created by ${Garrett} on 2018/9/8.
 * Contact me krouky@outlook.com
 */
public class ReaderPresenter extends BasePresenter<IReaderView, IModel> {
    private static final String TAG = "调试";
    private static final int PAGE_SIZE = 500;
    private int from;

    private BookDetailBean mBookDetailBean;
    private BookCollection mBookCollection;
    private ReaderHistory mReaderHistory;
    private ChapterItemBean mChapterItemBean;

    private BookService mBookService;
    private PayService mPayService;
    private UserService userService;
    private SubSidyService subSidyService;
    private BookshelfService mBookshelfService;
    private List<ChapterItemBean> mChapterList = new ArrayList<>();
    private PageFactory pageFactory;

    //缓存文件
    private File file;
    private String strChapterGSON = "";
    private ACache cache;

    private Set<Integer> downloadSet = new HashSet<>();

    private Integer chapterSum;
    private int desChapterIndex;
    private int desPageIndex;
    private int desCharIndex;
    private String desChapterId = "-1";//目标章节ID
    private String desChapterName;//目标章节名称
    public int currRequestChapterIndex = -1;//当前需要的chapterIndex

    private int mChapterPageNum;

    // 是否加载最新章节
    private boolean toNewChapter;
    private IFBook fBook;
    private Context mContext;

    private String lastChapterName;
    private String zsBookId = null;
    CyclicBarrier barrier = new CyclicBarrier(2);
    private boolean curChapterHasCache = false;
    private boolean getZsChapterListFailed = false;
    private boolean isAutoBuy = false;
    private boolean isFirstJoin = true;


    private boolean isAddShelf = true;

    public ReaderPresenter() {
    }

    public ReaderPresenter(Context mContext, IReaderView view, BookDetailBean bookDetailBean, boolean toNewChapter) {
        this.mContext = mContext;
        this.view = new WeakReference<IReaderView>(view).get();
        this.toNewChapter = toNewChapter;
        this.mBookDetailBean = bookDetailBean;
        from = Constant.START_FROM_BOOK_DETAIL;
        this.chapterSum = bookDetailBean.getChapterNum();
        this.lastChapterName = bookDetailBean.getUpdateChapterName();
        this.zsBookId = bookDetailBean.getZsBookId();
        desCharIndex = 0;
        desPageIndex = 0;
        if (toNewChapter) {//跳转到最新章节
            Log.i(TAG, "ReaderPresenter:chapterSum= " + chapterSum);
            desChapterIndex = chapterSum - 1;
            desChapterId = bookDetailBean.getUpdateChapterId();
            desChapterName = bookDetailBean.getUpdateChapterName();
        } else {
            desChapterIndex = 0;
            desChapterId = bookDetailBean.getFirstChapterId();
        }
        Log.i("记录", "ReaderPresenter: desChapterIndex" + desChapterIndex + "desPageIndex:" + desPageIndex + "desCharIndex:" + desCharIndex);

        init();
    }

    public ReaderPresenter(Context mContext, IReaderView view, BookCollection bookCollection) {
        this.mContext = mContext;
        this.view = new WeakReference<IReaderView>(view).get();
        this.mBookCollection = bookCollection;
        from = Constant.START_FROM_COLLECTION;
        desChapterIndex = bookCollection.getChapterIndex();
        mBookCollection.setChapterIndex(desChapterIndex);
        desPageIndex = bookCollection.getPageIndex();
        desCharIndex = bookCollection.getCharIndex();
        desChapterId = bookCollection.getHistoryChapterId();
        this.chapterSum = bookCollection.getChapterSum();
        this.lastChapterName = bookCollection.getLastChapterName();
        this.zsBookId = bookCollection.getZsBookId();
        Log.i("记录", "ReaderPresenter: desChapterIndex" + desChapterIndex + "desPageIndex:" + desPageIndex + "desCharIndex:" + desCharIndex);

        init();
    }

    public ReaderPresenter(Context mContext, IReaderView view, ReaderHistory readerHistory) {
        this.mContext = mContext;
        this.view = new WeakReference<IReaderView>(view).get();
        this.mReaderHistory = readerHistory;
        from = Constant.START_FROM_READ_HISTORY;
        desChapterIndex = readerHistory.getChapterIndex();
        mReaderHistory.setChapterIndex(desChapterIndex);
        desPageIndex = readerHistory.getPageIndex();
        desChapterId = readerHistory.getHistoryChapterId();
        desCharIndex = readerHistory.getCharIndex();
        Log.i("记录", "ReaderPresenter: desChapterIndex" + desChapterIndex + "desPageIndex:" + desPageIndex + "desCharIndex:" + desCharIndex);
        this.chapterSum = readerHistory.getChapterSum();
        this.lastChapterName = readerHistory.getLastChapterName();
        this.zsBookId = readerHistory.getZsBookId();
        init();
    }

    public ReaderPresenter(Context mContext, IReaderView view, ChapterItemBean bean, String lastChapterName) {
        this.mContext = mContext;
        this.view = new WeakReference<IReaderView>(view).get();
        this.mChapterItemBean = bean;
        from = Constant.START_FROM_CATALOGE;
        desChapterIndex = bean.getChapterIndex();
        mChapterItemBean.setChapterIndex(desChapterIndex);
        this.lastChapterName = lastChapterName;
//        desPageIndex = bean.getPageIndex();
        desChapterId = bean.getChapterId();
        desCharIndex = 0;
        this.chapterSum = bean.getChapterSum();
        this.zsBookId = bean.getZsBookId();
        init();
    }

    private void init() {
        if (desChapterId == null) {
//            view.errorBook();
            return;
        }

        FBookFactory fBookFactory = new FBookFactory();
        fBook = fBookFactory.createFBook(FBookType.ZHUISHU);
        if (mBookService == null) {
            mBookService = ApiImp.getInstance().getService(BookService.class);
        }
        if (mPayService == null) {
            mPayService = ApiImp.getInstance().getService(PayService.class);
        }
        if (userService == null) {
            userService = ApiImp.getInstance().getService(UserService.class);
        }
        if (subSidyService == null) {
            subSidyService = ApiImp.getInstance().getService(SubSidyService.class);
        }
        if (mBookshelfService == null) {
            mBookshelfService = ApiImp.getInstance().getService(BookshelfService.class);
        }
        file = new File(view.getViewContext().getCacheDir(), getBookId() + (UserInstance.isLogin() ? UserInstance.getToken() : 0));
        if (!file.exists()) {
            file.mkdirs();
        }
        cache = ACache.get(file);
        if (chapterSum % PAGE_SIZE == 0) {
            mChapterPageNum = chapterSum / PAGE_SIZE;
        } else {
            mChapterPageNum = chapterSum / PAGE_SIZE + 1;
        }
        String chapterItemJson = ACache.get(file).getAsString(getBookId() + "目录");
        if (!TextUtils.isEmpty(chapterItemJson)) {
            Log.i(TAG, "init: 缓存目录");
            try {
                mChapterList.clear();
                mChapterList = ReSouApplication.gson.fromJson(chapterItemJson, new TypeToken<List<ChapterItemBean>>() {
                }.getType());
            } catch (Exception e) {
                Log.i(TAG, "init: " + e.getMessage());
            }
        } else {
            Log.i(TAG, "init: 无缓冲目录");
        }
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            view.refreshPageView();
        }
    };

    @Override
    public void onCreate(@NonNull LifecycleOwner owner) {
        super.onCreate(owner);
        initData();

    }

    /**
     * 调取书籍是否下架
     * 是否添加到书架
     * 获取目录
     * 初始化工厂
     */
    private void initData() {
        if (desChapterId == null) {
            view.errorBook();
            return;
        }
        /**
         * 检测是否下架
         */
        checkUnshelf(UserInstance.getToken(), getBookId());
        quearisAddShelf();
        /**
         *获取目录列表
         */
        getCatalogue(getBookId(), UserInstance.getToken(), DeviceUtils.getIMEI(view.getViewContext()), getDesChapterIndex());
        pageFactory = new PageFactory(mContext, this, desChapterIndex < 0 ? 0 : desChapterIndex, desPageIndex, desCharIndex, getBookId(), chapterSum, toNewChapter);
        view.initPageView(pageFactory);
        view.getViewContext().registerReceiver(mReceiver, new IntentFilter("com.resou.reader.reader.p.readerpresenter"));
    }

    @Override
    public void onDestroy(@NonNull LifecycleOwner owner) {
        if (desChapterId != null) {
            view.getViewContext().unregisterReceiver(mReceiver);
        }
        super.onDestroy(owner);
    }

    public String getBookId() {
        switch (from) {
            case Constant.START_FROM_COLLECTION:
                return mBookCollection.getBookId() == null ? "" : mBookCollection.getBookId();
            case Constant.START_FROM_READ_HISTORY:
                return mReaderHistory.getBookId() == null ? "" : mReaderHistory.getBookId();
            case Constant.START_FROM_CATALOGE:
                return mChapterItemBean.getBookId() == null ? "" : mChapterItemBean.getBookId();
            case Constant.START_FROM_BOOK_DETAIL:
            default:
                if (mBookDetailBean != null) {
                    return mBookDetailBean.getId() == null ? "" : mBookDetailBean.getId();
                } else {
                    return "";
                }
        }
    }

    public int getDesChapterIndex() {
        switch (from) {
            case Constant.START_FROM_COLLECTION:
                return mBookCollection.getChapterIndex();
            case Constant.START_FROM_READ_HISTORY:
                return mReaderHistory.getChapterIndex();
            case Constant.START_FROM_CATALOGE:
                return mChapterItemBean.getChapterIndex();
            case Constant.START_FROM_BOOK_DETAIL:
            default:
                return toNewChapter ? chapterSum - 1 : 0;
        }
    }

    public String getBookName() {
        switch (from) {
            case Constant.START_FROM_COLLECTION:
                return mBookCollection.getName();
            case Constant.START_FROM_READ_HISTORY:
                return mReaderHistory.getName();
            case Constant.START_FROM_CATALOGE:
                return mChapterItemBean.getBookName();
            case Constant.START_FROM_BOOK_DETAIL:
            default:
                return mBookDetailBean.getNovelName();
        }
    }

    public String getBookImage() {
        switch (from) {
            case Constant.START_FROM_COLLECTION:
                return mBookCollection.getPicUrl();
            case Constant.START_FROM_READ_HISTORY:
                return mReaderHistory.getPicUrl();
            case Constant.START_FROM_CATALOGE:
                return mChapterItemBean.getBookPic();
            case Constant.START_FROM_BOOK_DETAIL:
            default:
                return mBookDetailBean.getCoverUrl();
        }
    }

    public boolean isAutoBuy() {
        return isAutoBuy;
    }

    public void setIsAutoBuy(boolean isAutoBuy) {
        this.isAutoBuy = isAutoBuy;
    }

    public String getShareUrl() {
        switch (from) {
            case Constant.START_FROM_COLLECTION:
                return mBookCollection.getShareUrl();
            case Constant.START_FROM_READ_HISTORY:
                return mReaderHistory.getShareUrl();
            case Constant.START_FROM_CATALOGE:
                return mChapterItemBean.getShareUrl();
            case Constant.START_FROM_BOOK_DETAIL:
            default:
                return mBookDetailBean.getShareUrl();
        }
    }

    public String getDescription() {
        switch (from) {
            case Constant.START_FROM_COLLECTION:
                return mBookCollection.getDescription();
            case Constant.START_FROM_READ_HISTORY:
                return mReaderHistory.getDescription();
            case Constant.START_FROM_CATALOGE:
                return mChapterItemBean.getDescription();
            case Constant.START_FROM_BOOK_DETAIL:
            default:
                return mBookDetailBean.getNovelDescription();
        }
    }

    //判断是否使用追书
    private boolean ifUseZhuishu() {
        if (UserInstance.isLogin()) {
            LoginData loginData = UserInstance.getLoginData();
            int energy = Integer.valueOf(loginData.getEnergy());
            boolean ifBookFree = PreferenceUtil.getInstance(ReSouApplication.getRSApplication()).checkIfBookFree(loginData.getId() + "", getBookId());
            if ((energy != 0 || ifBookFree) && !TextUtils.isEmpty(zsBookId)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 多章节付费后重新获取章节列表
     */
    public void reGetCatalogue() {
        getCatalogue(getBookId(), UserInstance.getToken(), DeviceUtils.getIMEI(view.getViewContext()), pageFactory.getChapterIndex());
    }

    /**
     * 任务站已经存在，刷新新书籍数据
     */
    public void setOnNewIntent(Context mContext, IReaderView view, BookDetailBean bookDetailBean, boolean toNewChapter) {
        if (this.mContext == null) {
            this.mContext = mContext;
        }
        if (this.view == null) {
            this.view = view;
        }
        this.toNewChapter = toNewChapter;
        this.mBookDetailBean = bookDetailBean;
        from = Constant.START_FROM_BOOK_DETAIL;
        this.chapterSum = bookDetailBean.getChapterNum();
        this.lastChapterName = bookDetailBean.getUpdateChapterName();
        this.zsBookId = bookDetailBean.getZsBookId();
        desCharIndex = 0;
        desPageIndex = 0;
        if (toNewChapter) {//跳转到最新章节
            Log.i(TAG, "ReaderPresenter:chapterSum= " + chapterSum);
            desChapterIndex = chapterSum - 1;
            desChapterId = bookDetailBean.getUpdateChapterId();
            desChapterName = bookDetailBean.getUpdateChapterName();
        } else {
            desChapterIndex = 0;
            desChapterId = bookDetailBean.getFirstChapterId();
        }
        init();

        initData();
    }

    /**
     * 任务站已经存在 从目录进入；
     *
     * @param mContext
     * @param view
     * @param bean
     * @param lastChapterName
     */
    public void setOnNewIntent(Context mContext, IReaderView view, ChapterItemBean bean, String lastChapterName) {
        this.mContext = mContext;
        this.view = view;
        this.mChapterItemBean = bean;
        from = Constant.START_FROM_CATALOGE;
        desChapterIndex = bean.getChapterIndex();
        mChapterItemBean.setChapterIndex(desChapterIndex);
        this.lastChapterName = lastChapterName;
        desChapterId = bean.getChapterId();
        desCharIndex = 0;
        this.chapterSum = bean.getChapterSum();
        this.zsBookId = bean.getZsBookId();
        init();
        initData();
    }

    /**
     * 获取章节列表
     *
     * @param bookId @Link{BookService}
     */
    public void getCatalogue(final String bookId, final String token, final String device,
                             int targetChapterIndex) {
        if (targetChapterIndex < 0) {
            targetChapterIndex = 0;
        }
        if (ifUseZhuishu()) {
            getZsCatalog(this.zsBookId, this.lastChapterName, targetChapterIndex);
            getYwCatalog(bookId, token, device, targetChapterIndex);
        } else {
            getYwCatalog(bookId, token, device, targetChapterIndex);
        }
    }

    private void getZsCatalog(String zsBookId, String lastChapterName,
                              final int targetChapterIndex) {
        fBook.setLocker(barrier);
        fBook.getBookChapters(zsBookId, lastChapterName, new ZsChapterCallback() {
            @Override
            public void onGetChapters(ZsBookChapter zsBookChapter) {
                getZsChapterListFailed = false;
                List<ZsChapter> chapters = zsBookChapter.getChapters();
                ReaderManager.convertZsChapterToYwChapter(chapters, mChapterList, zsBookId, desChapterId);//追书目录，返回值修正index
//                pageFactory.setChapterIndex(desChapterIndex);
                afterGetChapterCatalog(desChapterIndex, mChapterList);
                if (!toNewChapter && isFirstJoin) {
                    isFirstJoin = false;
                    remoteChapter();
                }
            }

            @Override
            public void onGetChaptersFailed(String errorMsg) {
                getZsChapterListFailed = true;
                afterGetChapterCatalog(targetChapterIndex, mChapterList);
                DLog.e(TAG, errorMsg);
            }
        });
    }

    private void getYwCatalog(String bookId, String token, String device, int targetChapterIndex) {
        mBookService.getBookCatalogList(bookId, null, token, device)
                .flatMap(new Function<CommonData<ChapterDataBean<List<ChapterItemBean>>>, ObservableSource<List<ChapterItemBean>>>() {
                    @Override
                    public ObservableSource<List<ChapterItemBean>> apply(CommonData<ChapterDataBean<List<ChapterItemBean>>> chapterData) {
//                        final List<ChapterItemBean> list = chapterData.getData().getData();
                        mChapterList = chapterData.getData().getData();
                        return Observable.create(new ObservableOnSubscribe<List<ChapterItemBean>>() {
                            @Override
                            public void subscribe(ObservableEmitter<List<ChapterItemBean>> emitter) {
                                emitter.onNext(CacheUtils.initializeCacheSetting(file, mChapterList));//检查章节是否下载过
                                if (ifUseZhuishu()) {
                                    try {
                                        barrier.await(3, TimeUnit.SECONDS);//等待获取所有的章节列表
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    } catch (BrokenBarrierException e) {
                                        e.printStackTrace();
                                    } catch (TimeoutException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        });
                    }
                }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(this.bindLifecycle())
                .subscribe(new Consumer<List<ChapterItemBean>>() {
                    @Override
                    public void accept(List<ChapterItemBean> chapterItemBeans) {
                        strChapterGSON = ReSouApplication.gson.toJson(chapterItemBeans);
                        if (!TextUtils.isEmpty(strChapterGSON)) {
                            ACache.get(file).put(bookId + "目录", strChapterGSON);
                        }
                        if (chapterItemBeans.size() > 0) {
                            if (!toNewChapter && isFirstJoin) {
                                isFirstJoin = false;
                                remoteChapter();
                            }
                            if (mChapterList.isEmpty()) {
                                ToastUtil.makeShortToast("无数据");
                                return;//添加错误提示
                            }
                            if (targetChapterIndex > 0 && targetChapterIndex < mChapterList.size()) {
                                desChapterId = mChapterList.get(targetChapterIndex).getChapterId();
                            } else {
                                desChapterId = mChapterList.get(0).getChapterId();
                            }
                            if (!ifUseZhuishu())//如果不走追书， 走阅文下载
                            {
                                afterGetChapterCatalog(targetChapterIndex, mChapterList);
                            }
                        }
//                        view.firstInitFactory();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        throwable.printStackTrace();
                        view.dismissLoading();
                        if (mChapterList.size() > 0) {
                            afterGetChapterCatalog(targetChapterIndex, mChapterList);
//                            pageFactory.onChapterCached(pageFactory.getChapterIndex(), null, toNewChapter);
                            if (!isChapterHasCache(pageFactory.getChapterIndex())) {
                                if (!NetworkUtils.isNetworkConnected(mContext) && (pageFactory.getCurrentContentBean() == null)) {
                                    view.setSubSidyState();
                                }
                                pageFactory.onChapterCached(pageFactory.getChapterIndex(), null, toNewChapter);
                            }
                        }
                    }
                });
    }

    private synchronized void afterGetChapterCatalog(int currRequestChapterIndex, List<
            ChapterItemBean> mChapterList) {
        //检查view为NULL的根本问题， oncreate 和 readpresenter构造方法执行顺序可能有问题
        int i = 3;
        while (view == null) {//检查初始化的view
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            i--;
            if (i <= 0) {
                return;
            }
        }
        view.refresh(mChapterList);
        chapterSum = mChapterList.size();
        pageFactory.setChapterSum(chapterSum);
        onChapterChanged(currRequestChapterIndex);

        if (currRequestChapterIndex != -1) {
            if (currRequestChapterIndex <= mChapterList.size() - 1) {//用户当前正在等待这一章的数据，优先下载
                downloadSet.add(currRequestChapterIndex);
                checkOrDownLoadChapterContent(currRequestChapterIndex);
            } else {
                if (mChapterList.size() == 0) {
                    currRequestChapterIndex = 0;
                } else {
                    currRequestChapterIndex = mChapterList.size() - 1;
                }
                downloadSet.add(currRequestChapterIndex);
                checkOrDownLoadChapterContent(currRequestChapterIndex);
            }
        }
    }

    //    Thread thread = null;
    boolean isReqFinish = true;

    /**
     * 下载章节内容
     */
    public synchronized void checkOrDownLoadChapterContent(int chapterIndex) {
        String token = null;
        if (UserInstance.isLogin()) {
            token = UserInstance.getToken();
        }
        if (chapterIndex < mChapterList.size() - 1) {
            if (toNewChapter) {
                toNewChapter = false;
                reqCurChapter(chapterIndex, token, true);
            } else {
                reqCurChapter(chapterIndex, token, true);
                reqPreChapter(chapterIndex, token);
                reqNextChapter(chapterIndex, token);
            }

        } else if (chapterIndex == mChapterList.size() - 1) {
            if (toNewChapter) {
                toNewChapter = false;
                reqCurChapter(chapterIndex, token, false);
            } else {
                reqCurChapter(chapterIndex, token, false);
                reqPreChapter(chapterIndex, token);
            }

        } else {
            Log.i(TAG, "checkOrDownLoadChapterContent: 下载章节内容");
            reqBookReading(chapterIndex, token, desChapterId, false, false, false, true);//请求当前章节内容， 如果章节内容没有缓存过
        }
    }

    /**
     * 下载章节内容
     */
    public void checkOrDownLoadChapterContent2(int chapterIndex) {
        String token = null;
        if (UserInstance.isLogin()) {
            token = UserInstance.getToken();
        }
        if (chapterIndex < mChapterList.size() - 1) {
            reqCurChapter(chapterIndex, token, true);
            reqNextChapter(chapterIndex, token);
        } else if (chapterIndex == mChapterList.size() - 1) {
            reqPreChapter(chapterIndex, token);
            reqCurChapter(chapterIndex, token, false);
        } else {
            Log.i(TAG, "checkOrDownLoadChapterContent2: 下载章节内容");
            reqBookReading(chapterIndex, token, desChapterId, false, false, false, false);//请求当前章节内容， 如果章节内容没有缓存过
        }
    }
//    public void getOnlineContentAfterPay(int chapterIndex)
//    {
//        String token = null;
//        if (UserInstance.isLogin()) {
//            token = UserInstance.getToken();
//        }
//        if(token == null) return;
//        if (chapterIndex < mChapterList.size() - 1)
//        {
//            reqCurChapter(chapterIndex, token, true);
//        }
//
//    }

    /**
     * 请求上一章节的数据
     *
     * @param chapterIndex
     * @param token
     */
    private synchronized void reqPreChapter(int chapterIndex, String token) {
        Log.i(TAG, "------------------------------------reqNextChapter: 上前章节内容-------------------------------------");
        if (chapterIndex <= 0) {
            return;
        }
        int reqPreChapterIndex = chapterIndex - 1;
        String jsonStr = ACache.get(file).getAsString(String.valueOf(reqPreChapterIndex));
        if (TextUtils.isEmpty(jsonStr))
            Log.i(TAG, "reqPreChapter: 下载章节内容");
        reqBookReading(reqPreChapterIndex, token, mChapterList.get(reqPreChapterIndex).getChapterId(), false, false, true, true);
    }

    /**
     * 请求下一章节的数据
     *
     * @param chapterIndex
     * @param token
     */
    private void reqNextChapter(int chapterIndex, String token) {
        Log.i(TAG, "------------------------------------reqNextChapter: 下章节内容-------------------------------------");

        int reqNextChapterIndex = chapterIndex + 1;
        String jsonStr = ACache.get(file).getAsString(String.valueOf(reqNextChapterIndex));
        if (!TextUtils.isEmpty(jsonStr)) {
            BookContentBean bean = ReSouApplication.gson.fromJson(jsonStr, BookContentBean.class);
            if (bean != null && "1".equals(bean.getIsVip()) && "0".equals(bean.getIsPay())) {
                Log.i(TAG, "reqNextChapter: jsonStr！=null下载章节内容");

                reqBookReading(reqNextChapterIndex, token, mChapterList.get(reqNextChapterIndex).getChapterId(), false, false, false, false);
            }
        } else {
            Log.i(TAG, "reqNextChapter: jsonStr==null下载章节内容");

            reqBookReading(reqNextChapterIndex, token, mChapterList.get(reqNextChapterIndex).getChapterId(), false, false, false, false);//请求下一个章节的内容
        }
    }

    /**
     * 请求当前章节内容
     *
     * @param chapterIndex
     * @param token
     * @param b
     */
    private synchronized void reqCurChapter(int chapterIndex, String token, boolean b) {
        Log.i(TAG, "------------------------------------reqNextChapter: 当前章节内容-------------------------------------");

        String jsonStr = ACache.get(file).getAsString(String.valueOf(chapterIndex));
        if (!TextUtils.isEmpty(jsonStr)) {
            BookContentBean bean = ReSouApplication.gson.fromJson(jsonStr, BookContentBean.class);
            if (bean != null && "1".equals(bean.getIsVip()) && "0".equals(bean.getIsPay())) {
                String desChapterId = mChapterList.get(chapterIndex).getChapterId();
                Log.i(TAG, "reqCurChapter: jsonStr!=null当前章节内容");
                reqBookReading(chapterIndex, token, desChapterId, true, b, false, true);
            }
        } else {
            String desChapterId = mChapterList.get(chapterIndex).getChapterId();
            Log.i(TAG, "reqCurChapter: 当前章节ChapterId==" + desChapterId);
            reqBookReading(chapterIndex, token, desChapterId, true, b, false, true);//请求当前的书籍内容, 如果章节内容没有缓存过
        }
    }

    /**
     * 是否缓存
     */
    public boolean isCache() {
        String jsonStr = ACache.get(file).getAsString(String.valueOf(desChapterIndex));
        if (TextUtils.isEmpty(jsonStr)) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 检测是否需要自动购买
     *
     * @param token
     * @param bookId
     * @param desChapterId
     * @param mChapterIndex
     * @param price
     * @param isRefresh
     */
    public synchronized void checkAutoBuy(String token, String bookId, String desChapterId,
                                          int mChapterIndex, int price, boolean isRefresh) {
        mBookService.checkAutoBuy(token, bookId)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .as(this.bindLifecycle())
                .subscribe(new Consumer<Result<Boolean>>() {
                    @Override
                    public void accept(Result<Boolean> result) {
                        isAutoBuy = result.getData();
                        pageFactory.setIsAutoBuy(isAutoBuy);
                        Log.i(TAG, "-------------------accept: 是否自动购买：" + isAutoBuy);
                        if (isAutoBuy) {
                            LoginData loginData = UserInstance.getLoginData();
                            if (loginData.getBlance() + loginData.getGiftBlance() + Integer.valueOf(loginData.getEnergy()) >= price) {
                                singleChapterPay(desChapterId, mChapterIndex, price, isRefresh);
                            } else {
                                setCheckAutoBuy(UserInstance.getToken(), bookId, "close");
                            }
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                    }
                });
    }

    /**
     * 设置自动购买
     *
     * @param token
     * @param bookId 书籍id
     * @param auto   是否自动购买
     */
    public void setCheckAutoBuy(String token, String bookId, String auto) {
        mBookService.setAutoBuy(token, bookId, auto)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .as(this.bindLifecycle())
                .subscribe(new Consumer<Result>() {
                    @Override
                    public void accept(Result result) {
                        if (result.getCode() == 0) {
                            isAutoBuy = !isAutoBuy;
                            if (!isAutoBuy) {
                                pageFactory.setIsAutoBuy(false);
                            }
                            view.refreshPayView();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                    }
                });
    }

    /**
     * 分享后时间设置
     */
    public void addShareTime() {
        mBookService.addShareTime(UserInstance.getToken())
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .as(this.bindLifecycle())
                .subscribe(new Consumer<Result<ShareTimeBean>>() {
                    @Override
                    public void accept(Result<ShareTimeBean> result) {
                        if (result.getCode() == 0) {
                            view.refreshShareTime(result.getData());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                    }
                });
    }

    /**
     * 设置自动购买
     */
    public void setCheckAutoBuyStyle() {
        view.refreshPayView();
    }


    /**
     * 获取用户信息
     *
     * @param token
     */
    public void getUserInfo(String token) {
        userService.getUserInfo(token)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .as(this.bindLifecycle())
                .subscribe(new Consumer<Result<UserInfoBean>>() {
                    @Override
                    public void accept(Result<UserInfoBean> result) {
                        if (result.getCode() == 0 && result.getData() != null) {
                            UserInfoBean.UBean uBean = result.getData().getU();
                            if (uBean != null) {
                                UserInstance.saveUserInfo(uBean);
                                UserInstance.setToken(token);
                                view.refreshPayView();
                            }
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                    }
                });
    }

    /***
     *设置阅读模式
     * @param subSidyType 阅读模式   0.，省钱（有广告），1 vip （无广告）2 普通（正常购买模式）
     */
    public void setSubSidy(int subSidyType) {
        subSidyService.setSubSidyModel(UserInstance.getToken(), subSidyType)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .as(this.bindLifecycle())
                .subscribe(new Observer<Result<SubSidyDetailBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Result<SubSidyDetailBean> subSidyDetailBeanResult) {
                        PreferenceUtil.getInstance(ReSouApplication.getRSApplication()).saveSubSidyStateValue(subSidyType);
                        view.setSubSidySucess();
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                        view.setSubSidySucess();
                    }
                });
    }

    /**
     * 请求阅读器内容
     *
     * @param chapterIndex
     * @param token
     * @param desChapterId
     * @param forceRefresh
     * @param showPage
     * @param isRefresh
     */
    private void reqBookReading(int chapterIndex, String token, String
            desChapterId, boolean forceRefresh, final boolean showPage, boolean isPrePage,
                                boolean isRefresh) {
        Log.i(TAG, "reqBookReading:chapterIndex= " + chapterIndex + "desChapterId" + desChapterId);
        synchronized (desChapterId) {
            try {
                Thread.sleep(20);   // 休眠20毫秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (!forceRefresh && ifUseZhuishu() && cache.getAsString("zs" + desChapterId) != null)//章节已经下载过了，不用再请求接口
            {
                downloadSet.remove(chapterIndex);
                return;
            }
            int defaultReadPath = getDefaultReadPath(chapterIndex);

            mBookService.getBookContentV2(token, getBookId(), desChapterId, defaultReadPath)
                    .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                    .as(this.bindLifecycle())
                    .subscribe(new Consumer<Result<BookContentBean>>() {
                        @Override
                        public void accept(Result<BookContentBean> bookContentBeanResult) {
//                            isReqFinish = true;
                            if (bookContentBeanResult != null && bookContentBeanResult.getData() != null && bookContentBeanResult.getData().getUnshelf() == 1) {
//                                Log.i(TAG, "accept:是否缓存 " + isCache());
                                if (!isChapterHasCache(chapterIndex) && pageFactory.getChapterIndex() == chapterIndex) {
                                    ToastUtil.makeShortToast("书籍已下架");
                                    pageFactory.setUnShelf(true);
                                    pageFactory.onChapterCached(chapterIndex, bookContentBeanResult.getData(), toNewChapter);
                                }
                                return;
                            } else {
                                pageFactory.setUnShelf(false);
                            }
                            if (bookContentBeanResult.getCode() == 200 || bookContentBeanResult.getCode() == 100) {
                                getZsChapterContent(bookContentBeanResult, chapterIndex, showPage);
                            } else if (bookContentBeanResult.getCode() == 0) {
                                dowloadYwChapterContent(bookContentBeanResult, chapterIndex, isPrePage, isRefresh);
                                toNewChapter = false;
                            }
                            if (forceRefresh) {
                                /**
                                 * 刷新时间
                                 */
                                refreshShareTime(bookContentBeanResult.getData());
                            }
//                            view.dismissLoading();
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) {
                            if (!isChapterHasCache(chapterIndex)) {
                                if (!NetworkUtils.isNetworkConnected(mContext) && (pageFactory.getCurrentContentBean() == null)) {
                                    view.setSubSidyState();
                                }
                                pageFactory.onChapterCached(chapterIndex, null, toNewChapter);
                            }
//                            pageFactory.setUnShelf(true);
                            view.dismissLoading();
                        }
                    });
        }
    }

    private int getDefaultReadPath(int chapterIndex) {
        int defaultReadPath = 0;
        if (mChapterList.size() > 0) {
            ChapterItemBean chapterItemBean;
            try {
                chapterItemBean = mChapterList.get(chapterIndex);
            } catch (IndexOutOfBoundsException e) {
                chapterItemBean = mChapterList.get(chapterIndex - 2);
            }
            if (TextUtils.isEmpty(chapterItemBean.getZsChapterLink())) {
                defaultReadPath = 1;
            }
        }
        if (getZsChapterListFailed || !ifUseZhuishu()) {
            defaultReadPath = 1;
        }
        return defaultReadPath;
    }

    /**
     * 获取追书详情
     *
     * @param bookContentBeanResult
     * @param chapterIndex
     * @param showPage
     */
    private void getZsChapterContent(Result<BookContentBean> bookContentBeanResult,
                                     int chapterIndex, boolean showPage) {
        BookContentBean bean = bookContentBeanResult.getData();
        bean.setChapterName(mChapterList.get(chapterIndex).getChapterName());//设置章节名称
        int totalChapterNum = mChapterList.size();
        if (totalChapterNum > 0) {
            ChapterItemBean chapterItem = null;
            if (chapterIndex > totalChapterNum) {
                chapterItem = mChapterList.get(totalChapterNum - 1);
            } else {
                chapterItem = mChapterList.get(chapterIndex);
            }
            bean.setZsChapterLink(chapterItem.getZsChapterLink());
            bean.setZsChapterSuffix(chapterItem.getZsChapterIdSuffix());
            fBook.getBookChapterContent(chapterItem.getZsChapterLink(), new ZsFBookCallback() {
                @Override
                public void onSuccess(ZsBookChapterContent zsBookChapterContent) {
                    String body = "       " + zsBookChapterContent.getChapter().getBody();
                    bean.setContent(body.replace("\n", "\n       "));
                    String cacheKey = "zs" + bean.getChapterId();
                    if (bean.getZsChapterSuffix() != null) {
                        cacheKey = cacheKey + bean.getZsChapterSuffix();
                    }
                    ACache.get(file).put(cacheKey, ReSouApplication.gson.toJson(bean));
                    mChapterList.get(chapterIndex).setCached(true);
                    if (showPage) {
                        downloadSet.remove(chapterIndex);
                        pageFactory.onChapterCached(chapterIndex, bean, toNewChapter);
                        currRequestChapterIndex = -1;
                        Loading.getInstance().dismiss();
                    }
                }

                @Override
                public void onFailed(String errorMsg) {
                    downloadSet.remove(chapterIndex);
                }
            });
        } else {
            //获取阅文的章节列表
        }
    }

    /**
     * 下载章节内容
     *
     * @param bookContentBeanResult
     * @param chapterIndex
     * @param isRefresh
     * @p
     */
    private synchronized void dowloadYwChapterContent(Result<BookContentBean> bookContentBeanResult, int chapterIndex, boolean isPrepage, boolean isRefresh) {
        BookContentBean bean = bookContentBeanResult.getData();
        if (bean == null) {
            ToastUtil.makeShortToast("服务器异常");
            return;
        }
        if (mChapterList.size() != 0) {
            bean.setChapterName(mChapterList.get(chapterIndex).getChapterName());//设置章节名称
            mChapterList.get(chapterIndex).setCached(true);
            if (0 == PreferenceUtil.getInstance(ReSouApplication.getRSApplication()).getSubSidyStateValue()) {
                mChapterList.get(chapterIndex).setIsPay("1");
            }
        }
        ACache.get(file).put(bean.getChapterId(), ReSouApplication.gson.toJson(bean));
        downloadSet.remove(chapterIndex);
        pageFactory.onChapterCached(chapterIndex, bean, toNewChapter);
        if (!isPrepage) {
            if (bean != null && "1".equals(bean.getIsVip()) && "0".equals(bean.getIsPay()) && !pageFactory.isSubSidyState()) {
                checkAutoBuy(UserInstance.getToken(), getBookId(), bean.getChapterId(), chapterIndex, Integer.valueOf(bean.getVipPrice()), isRefresh);
            }
        }
        currRequestChapterIndex = -1;
        Loading.getInstance().dismiss();
    }


    public void removeCacheChangeStatus(int num) {
        if (num > 0) {
            int temp = 0;
            int tempChapterIndex = pageFactory.getChapterIndex();
            while (temp < num && tempChapterIndex < mChapterList.size()) {
                ChapterItemBean bean = mChapterList.get(tempChapterIndex++);
                if (!"1".equals(bean.getIsPay())) {
                    bean.setCached(false);
                    ACache.get(file).remove(bean.getChapterId());
                    bean.setIsPay("1");
                } else {
                    continue;
                }
                temp++;
            }
        }
    }

    public void removeCurrCache(int chapterIndex) {
        if (chapterIndex < mChapterList.size()) {
            ChapterItemBean bean = mChapterList.get(chapterIndex);
            bean.setCached(false);
            ACache.get(file).remove(bean.getChapterId());
        }
    }

    public int getChapterNum() {
        return chapterSum == null ? 1 : chapterSum;
    }


    /**
     * @return 是否已经加入了书架
     */
    @SuppressLint("CheckResult")
    public boolean isAlreadyAddShelf() {
//        List<BookCollection> collections = LitePal.select("bookId").where("bookId = \'" + getBookId() + "\'").find(BookCollection.class);
//        return collections != null && collections.size() > 0;
        Log.i(TAG, "isAlreadyAddShelf: " + isAddShelf);
        return isAddShelf;
    }

    /**
     * 查询书籍是否加入书架
     */
    private void quearisAddShelf() {
        mBookshelfService.checkIsCollected(getBookId(), UserInstance.getToken())
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .as(this.bindLifecycle())
                .subscribe(new Consumer<Result<Integer>>() {
                    @Override
                    public void accept(Result<Integer> result) throws Exception {
                        if (result.getData() != null && (result.getData() == 1)) {
                            isAddShelf = true;
                        } else {
                            isAddShelf = false;
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Log.i(TAG, "accept: " + throwable.getMessage());
                    }
                });
    }

    /**
     * 分享
     */
    public void share(boolean isFreeRead) {
//        Log.i(TAG, "share: " + "我正在看《" + getBookName() + "》" + getDescription());
//        UMWeb web = new UMWeb("https://m.resouxs.com/bookDetail/" + getBookId());
//        web.setTitle("平台补贴，海量正版书籍免费看！");//标题
//        web.setDescription("我正在看《" + getBookName() + "》" + getDescription());
        String shareUrl = "http://share.resouxs.com/details.html?id=" + getBookId() + "&app=app";
        UMWeb web = new UMWeb(shareUrl);
        web.setTitle("平台补贴，海量正版书籍免费看！");//标题
        web.setDescription("我正在看《" + getBookName() + "》" + getDescription() + "");
        new ShareAction((Activity) view.getViewContext())
                .withMedia(web)
                .setDisplayList(SHARE_MEDIA.QQ, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.QZONE)
                .setCallback(isFreeRead ? shareFreeListener : shareListener).open();
        web.setThumb(new UMImage(mContext, getBookImage()));
    }

    /**
     * 分享监听
     */
    private UMShareListener shareFreeListener = new UMShareListener() {
        /**
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
            switch (platform) {
                case WEIXIN:
                case WEIXIN_CIRCLE:
                    if (!WXUtils.isWeixinAvilible(mContext)) {
                        ToastUtil.makeShortToast("您未安装微信，请选择其他分享方式");
                        return;
                    }
                    break;
                case QZONE:
                case QQ:
                    if (!WXUtils.isQQClientAvailable(mContext)) {
                        ToastUtil.makeShortToast("您未安装QQ，请选择其他分享方式");
                        return;
                    }
                    break;
            }
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    view.showShareSuccess();
                    addShareTime();
                }
            }, 3000);
        }

        /**
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {


        }

        /**
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {

        }

        /**
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
        }
    };
    private UMShareListener shareListener = new UMShareListener() {
        /**
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
            switch (platform) {
                case WEIXIN:
                case WEIXIN_CIRCLE:
                    if (!WXUtils.isWeixinAvilible(mContext)) {
                        ToastUtil.makeShortToast("您未安装微信，请选择其他分享方式");
                        return;
                    }
                    break;
                case QZONE:
                case QQ:
                    if (!WXUtils.isQQClientAvailable(mContext)) {
                        ToastUtil.makeShortToast("您未安装QQ，请选择其他分享方式");
                        return;
                    }
                    break;
            }
        }

        /**
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            SnsPlatform snsPlatform = platform.toSnsPlatform();
//            addShareTime();
        }

        /**
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
        }

        /**
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
        }
    };

    /**
     * View 现在展示的章节索引,view onDraw的时候回调
     *
     * @param chapterIndex 当前章节索引
     */
    public void onChapterDrawed(int chapterIndex) {
        //前后缓存四章
//        for (int i = chapterIndex - 2; i < chapterIndex + 2; i++) {
//            if (i >= 0 && i < mChapterList.size()) {
////                Log.d(TAG, "request i == " + i);
//                getChapterContent(i);
//            }
//        }
    }

    public List<ChapterItemBean> getChapterList() {
        return mChapterList;
    }

    /**
     * 是否存在缓存目录
     *
     * @return
     */
    public boolean isCacheChapterList() {
        return mChapterList.size() > 0;
    }

    /**
     * 获取章节内容
     *
     * @param chapterIndex 章节索引
     * @return null or BookContentBean
     */
    private BookContentBean getChapterContentByChapterList(final int chapterIndex) {
        if (chapterIndex > mChapterList.size() - 1) {//说明目录还未加载成功
            currRequestChapterIndex = chapterIndex;
            return null;
        }
        if (mChapterList.get(chapterIndex).isCached()) {
            //读取缓存
            String jsonStr = cache.getAsString(mChapterList.get(chapterIndex).getChapterId());
            Loading.getInstance().dismiss();
            return ReSouApplication.gson.fromJson(jsonStr, BookContentBean.class);
        } else {
            //下载
            currRequestChapterIndex = chapterIndex;
            if (!downloadSet.contains(chapterIndex)) {
                downloadSet.add(chapterIndex);
                checkOrDownLoadChapterContent(chapterIndex);
            }
            return null;
        }
    }

    /**
     * 购买成功后 获取章节内容
     *
     * @param chapterIndex
     * @param chapterPayed 支付类型
     * @param isRefresh    是否需要刷新当前章节与下一章节
     * @return
     */
    public BookContentBean getChapterContent(final int chapterIndex, int chapterPayed,
                                             boolean isRefresh) {
        if (chapterPayed == 3) {
            for (ChapterItemBean bean : mChapterList) {
                bean.setIsPay("1");
            }
            view.refresh(mChapterList);
        }
        if (mChapterList.size() != 0 && ifUseZhuishu()) {
            String reqChapterId = getReqChapterId(chapterIndex);
            String jsonStr = ACache.get(file).getAsString(reqChapterId);
            if (jsonStr == null) {
//                view.showLoading();
                curChapterHasCache = false;
                Log.i(TAG, "getChapterContent: 购买成功后获取章节内容");
                checkOrDownLoadChapterContent(chapterIndex);
                return null;
            }
            BookContentBean bookContentBean = ReSouApplication.gson.fromJson(jsonStr, BookContentBean.class);
            bookContentBean.setIsPay("1");
            if (file != null && bookContentBean != null) {
                ACache.get(file).put(reqChapterId, ReSouApplication.gson.toJson(bookContentBean));
            }
            pageFactory.onChapterCached(chapterIndex, bookContentBean, false);
//            dismissLoading();
            return bookContentBean;
        } else {
            curChapterHasCache = false;
            /**
             * 无需刷新
             * 请求当前页  并且 不用刷新页面
             */
            if (isRefresh) {
                pageFactory.startChapterFromBegin();
//                checkOrDownLoadChapterContent(chapterIndex);
            }
            checkOrDownLoadChapterContent2(chapterIndex);

            return null;
        }

    }

    /**
     * 查看远程进度
     */
    public void remoteChapter() {

        mBookService.quearBookRecordDetail(UserInstance.getToken(), getBookId())
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .as(this.bindLifecycle())
                .subscribe(new Observer<Result<BookDetailBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Result<BookDetailBean> bookDetailBeanResult) {
                        if (bookDetailBeanResult != null && bookDetailBeanResult.getData() != null && getDesChapterIndex() != bookDetailBeanResult.getData().getChapterIndex()) {
                            if (bookDetailBeanResult.getData().getChapterIndex() != 0) {
                                if (view != null) {
                                    view.toNewChapter(bookDetailBeanResult.getData());
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    String mChapterId = "";

    /***
     * 获取章节增加金额
     * @param chapterId
     * @param length
     * mChapterId 用于防止当前页或者切换章节两次调用添加金币
     *
     */
    public synchronized void getChapterAddMoney(String chapterId, int length) {
        if (mChapterId == chapterId) {
            return;
        }
        mChapterId = chapterId;
        Log.i("章节名", "getChapterAddMoney: " + chapterId);
        subSidyService.addBookChapterPrice(UserInstance.getToken(), getBookId(), chapterId, length)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .as(this.bindLifecycle())
                .subscribe(new Consumer<Result<String>>() {
                    @Override
                    public void accept(Result<String> shareTimeBeanResult) throws Exception {
                        getChapterAllMoney(chapterId, shareTimeBeanResult.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
//                        ToastUtil.makeShortToast("网络异常");
                    }
                });
    }

    /**
     * 获取全部补贴金额
     */
    public synchronized void getChapterAllMoney(String chapterId, String money) {
        subSidyService.getUserPrice(UserInstance.getToken(), getBookId(), chapterId)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .as(this.bindLifecycle())
                .subscribe(new Consumer<Result<ShareTimeBean>>() {
                    @Override
                    public void accept(Result<ShareTimeBean> shareTimeBeanResult) throws Exception {
                        view.refreshAddMoney(new ShareTimeBean(shareTimeBeanResult.getData().getUserPrice(), Float.valueOf(money)));
                        Log.i("章节名", "accept: getUserPrice=" + shareTimeBeanResult.getData().getUserPrice() + "money:" + money);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
//                        ToastUtil.makeShortToast("网络异常");
                    }
                });
    }


    /**
     * 获取章节内容
     *
     * @param chapterIndex 章节索引
     * @return BookContentBean
     */
    public synchronized BookContentBean getChapterContent(final int chapterIndex) {
        Log.i(TAG, "getChapterContent: 获取当前章节内容+" + chapterIndex);
        String jsonStr = null;
        if (chapterIndex == this.desChapterIndex) {//处理刚打开阅读器，希望直接加载特定章节时
            String reqChapterId = getReqChapterId(chapterIndex);
            if (file != null && reqChapterId != null) {
                jsonStr = ACache.get(file).getAsString(reqChapterId);
            }
            if (jsonStr != null) {
                curChapterHasCache = true;
                Loading.getInstance().dismiss();
                return ReSouApplication.gson.fromJson(jsonStr, BookContentBean.class);
            } else {
                curChapterHasCache = false;
                checkOrDownLoadChapterContent(chapterIndex);
                return null;
            }
        } else { //如果在阅读页面翻页的过程
//            return getChapterContentByChapterList(chapterIndex);
            String reqChapterId = getReqChapterId(chapterIndex);
            jsonStr = ACache.get(file).getAsString(reqChapterId);
            if (jsonStr != null) {
                curChapterHasCache = true;
//                if (!downloadSet.contains(chapterIndex)) {
//                    downloadSet.add(chapterIndex);
                checkOrDownLoadChapterContent(chapterIndex);
//                }
                Loading.getInstance().dismiss();
                return ReSouApplication.gson.fromJson(jsonStr, BookContentBean.class);
            } else if (mChapterList.size() != 0) {
                curChapterHasCache = false;
                showLoading(mContext.getString(R.string.loading));
//                if (!downloadSet.contains(chapterIndex)) {
//                    downloadSet.add(chapterIndex);
                if (toNewChapter) {
                    checkOrDownLoadChapterContent(getDesChapterIndex());
                    toNewChapter = false;
                } else {
                    checkOrDownLoadChapterContent(chapterIndex);
                }
//                }
                return null;
            } else {
                return null;
            }

        }
    }

    /**
     * 获取章节内容
     *
     * @param chapterIndex 章节索引
     * @return BookContentBean
     */
    public synchronized BookContentBean getChapterContent2(final int chapterIndex) {
        String jsonStr = null;
        if (chapterIndex == this.desChapterIndex) {//处理刚打开阅读器，希望直接加载特定章节时
            String reqChapterId = getReqChapterId(chapterIndex);
            if (file != null && reqChapterId != null) {
                jsonStr = ACache.get(file).getAsString(reqChapterId);
            }
            if (jsonStr != null) {
                curChapterHasCache = true;
                Loading.getInstance().dismiss();
                return ReSouApplication.gson.fromJson(jsonStr, BookContentBean.class);
            } else {
                curChapterHasCache = false;
                return null;
            }
        } else { //如果在阅读页面翻页的过程
            String reqChapterId = getReqChapterId(chapterIndex);
            jsonStr = ACache.get(file).getAsString(reqChapterId);
            if (jsonStr != null) {
                curChapterHasCache = true;
                Loading.getInstance().dismiss();
                return ReSouApplication.gson.fromJson(jsonStr, BookContentBean.class);
            } else if (mChapterList.size() != 0) {
                curChapterHasCache = false;
                return null;
            } else {
                return null;
            }

        }
    }

    private String getReqChapterId(int chapterIndex) {
        String reqChapterId = desChapterId;
        if (mChapterList.size() != 0 && chapterIndex < mChapterList.size()) {
            //第一次进入，目录没有加载出来不会走这个分支
            //TODO 后续目录需要缓存
            ChapterItemBean chapterItemBean = mChapterList.get(chapterIndex);
            if (!ifUseZhuishu() || getZsChapterListFailed || chapterItemBean.getZsChapterLink() == null) {
                reqChapterId = chapterItemBean.getChapterId();
            } else {
                reqChapterId = "zs" + chapterItemBean.getChapterId();
                if (chapterItemBean.getZsChapterIdSuffix() != null) {
                    reqChapterId = reqChapterId + chapterItemBean.getZsChapterIdSuffix();
                }
            }
        } else  //如果章节列表为空， 但是追书id不为空
        {
            if (ifUseZhuishu() && !getZsChapterListFailed) {
                reqChapterId = "zs" + reqChapterId;
            }
        }
        return reqChapterId;
    }

    /**
     * 检测书籍是否下架
     *
     * @param token
     * @param bookId
     */
    public synchronized void checkUnshelf(String token, String bookId) {
        mBookService.checkUnshelf(token, bookId)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .as(this.bindLifecycle())
                .subscribe(new Consumer<Result<BookDetailBean>>() {
                    @Override
                    public void accept(Result<BookDetailBean> bookDetailBeanResult) throws Exception {
                        if (bookDetailBeanResult != null) {
                            if ("1".equals(bookDetailBeanResult.getData().getUnshelf())) {
                                pageFactory.setUnShelf(true);
                                refreshPageView();
                            }
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        if (!NetworkUtils.isNetworkConnected(mContext)) {
                            ToastUtil.makeShortToast("网络异常");
                        } else {
                            ToastUtil.makeShortToast("数据异常，请稍后重试");
                        }
                    }
                });
    }

    public void refreshPageView() {
        view.refreshPageView();
    }

    /**
     * 通过索引获取章节名称
     *
     * @param chapterIndex 章节索引
     * @return chapterName
     */
    public String getChapterName(int chapterIndex) {
        if (mChapterList.size() <= chapterIndex) {
            return "";
        }
        return mChapterList.get(chapterIndex).getChapterName();
    }

    DecimalFormat df = new DecimalFormat("#0.00");

    /**
     * 章节进度值
     *
     * @param chapterIndex
     * @return
     */
    public String getPersentValue(float chapterIndex) {
        Log.i(TAG, "getPersentValue: mChapterList.size()====" + mChapterList.size());
        Log.i(TAG, "getPersentValue:chapterIndex ===" + chapterIndex);
        try {
            if (mChapterList.size() <= (chapterIndex + 1)) {
                return "100";
            } else {
                float value = (float) ((100 * (chapterIndex + 1)) / (mChapterList.size()));
//                if (value > 99) {
//                    return "100";
//                } else if (value < 1) {
//                    return "" + df.format(value);
//                } else {
//                }
                return df.format(value);
            }
        } catch (Exception e) {
            return "0";
        }
    }

    /**
     * 加入历史
     */
    public ReaderHistory addToHistory(String historyChapterName, String historyChapterId,
                                      int chapterIndex, int pageIndex, int charIndex) {
        if (from == Constant.START_FROM_BOOK_DETAIL) {
            return DataSupport.getInstance().saveReadHistory(mBookDetailBean, historyChapterName, historyChapterId, chapterIndex, pageIndex, charIndex);
        } else if (from == Constant.START_FROM_COLLECTION) {
            return DataSupport.getInstance().saveReadHistory(mBookCollection, historyChapterName, historyChapterId, chapterIndex, pageIndex, charIndex);
        } else {
            return null;
        }
    }

    /**
     * 章节批量付费
     */
    public void chapterBatchPay(String chapterId, String chapterName) {
        BatchPayActivity.startActivityForResult((Activity) view.getViewContext(), getBookId(), getBookName(), chapterId, chapterName, START_MULTI_PAY_REQUEST_CODE);
    }

    /**
     * 单章节购买
     *
     * @param chapterId
     * @param chapterIndex
     * @param price
     * @param isRefresh    是否是当前页
     */
    public synchronized void singleChapterPay(String chapterId, int chapterIndex, int price,
                                              boolean isRefresh) {
        Log.i("购买", "singleChapterPay: 购买：" + chapterIndex);
        if (ifUseZhuishu()) {
            activityPay(chapterId, chapterIndex, price, 1);
        } else {
            if (isRefresh) {
                view.showLoading("付费中...");
            }
            mPayService.singleChapterPay(UserInstance.getToken(), getBookId(), getBookName(), chapterId, getChapterName(chapterIndex), price)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .as(this.bindLifecycle())
                    .subscribe(payResultBeanResult -> {
                        afterPaidSingleChapter(chapterId, chapterIndex, payResultBeanResult, isRefresh);
                    }, throwable -> {
//                        Toast.makeText(view.getViewContext(), throwable.getMessage(), Toast.LENGTH_SHORT).show();
                        ToastUtil.makeShortToast(throwable.getMessage());
                        throwable.printStackTrace();
                        pageFactory.chapterPayError(-100, throwable.getMessage());
                    });
        }
        Loading.getInstance().dismiss();
    }


    private void activityPay(String chapterId, int chapterIndex, int price, int payType) {
        mPayService.activityChapterPay(UserInstance.getToken(), getBookId(), getBookName(), chapterId, getChapterName(chapterIndex), price, payType)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(this.bindLifecycle())
                .subscribe(payResultBeanResult -> {
                    afterPaidSingleChapter(chapterId, chapterIndex, payResultBeanResult, true);
                }, throwable -> {
//                    Toast.makeText(view.getViewContext(), throwable.getMessage(), Toast.LENGTH_SHORT).show();
                    ToastUtil.makeShortToast(throwable.getMessage());
                    throwable.printStackTrace();
                    pageFactory.chapterPayError(-100, throwable.getMessage());
                });
    }

    /**
     * 章节付费成功后的逻辑
     *
     * @param chapterId
     * @param chapterIndex
     * @param payResultBeanResult
     * @param isRefresh
     */
    private synchronized void afterPaidSingleChapter(String chapterId, int chapterIndex, Result<
            PayResultBean> payResultBeanResult, boolean isRefresh) {
        int code = payResultBeanResult.getCode();
        if (code == 0) {
            if (mChapterList != null) {
                if (isRefresh) {
                    view.showLoading("付费成功，加载中...");
                }
                ACache.get(file).remove(chapterId);
                mChapterList.get(chapterIndex).setCached(false);
                mChapterList.get(chapterIndex).setIsPay("1");
                PayResultBean bean = payResultBeanResult.getData();
                UserInstance.getLoginData().setBlance(bean.getCurrency());
                UserInstance.getLoginData().setGiftBlance(bean.getVoucher());
                pageFactory.chapterPaySuccess(isRefresh);
            } else {
                pageFactory.chapterPayError(code, payResultBeanResult.getMsg());
            }
            // 购买成功获取鉴权之后的BookContentBean
        }
    }

    /**
     * 全本购买
     *
     * @param chapterId
     * @param price
     */
    public void allChapterPay(String chapterId, int price) {
        mPayService.allChapterPay(UserInstance.getToken(), getBookId(), getBookName(), chapterId, price)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(this.bindLifecycle())
                .subscribe(new Consumer<Result<PayResultBean>>() {
                    @Override
                    public void accept(Result<PayResultBean> payResultBeanResult) throws Exception {
                        view.showLoading("付费成功，加载中...");
                        PayResultBean bean = payResultBeanResult.getData();
                        UserInstance.getLoginData().setBlance(bean.getCurrency());
                        UserInstance.getLoginData().setGiftBlance(bean.getVoucher());
                        pageFactory.chapterPaySuccess(true);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
//                        Toast.makeText(view.getViewContext(), throwable.getMessage(), Toast.LENGTH_SHORT).show();
                        ToastUtil.makeShortToast(throwable.getMessage());
                        throwable.printStackTrace();
                        pageFactory.chapterPayError(-100, throwable.getMessage());
                    }
                });
    }

    /**
     * 启动推荐页面
     */
    public void startToComment() {
        CommentListActivity.start(view.getViewContext(), getBookId(), getBookName());
    }

    /**
     * 加入书架
     *
     * @param isExit 是否退出阅读器
     */
    public synchronized void addToBookShelf(boolean isExit) {
        Log.d(TAG, "addToBookShelf: from" + from);
        if (from == Constant.START_FROM_BOOK_DETAIL) {
            if (pageFactory.getCurrentContentBean() != null) {
                pageFactory.saveHistoryAndCollection();
                if (NetworkUtils.isNetworkConnected(ReSouApplication.getContext())) {
                    uploadBookToShelf(isExit);
                }
                pageFactory.addCollection(mBookDetailBean);
//                DataSupport.getInstance().saveCollection(mBookDetailBean, getChapterName(pageFactory.getChapterIndex()),
//                        pageFactory.getCurrentContentBean().getChapterId(), pageFactory.getChapterIndex(), 3, 0);
                Log.d(TAG, "addToBookShelf onNext: 阅读器退出时保存书籍到本地成功");
            }
        } else {
            if (NetworkUtils.isNetworkConnected(ReSouApplication.getContext())) {
                uploadBookToShelf(isExit);
                mBookService.getBookDetail(UserInstance.getToken(), getBookId(), "app", null)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .as(this.bindLifecycle())
                        .subscribe(commonDataResult -> {
                            CommonData<BookDetailBean> commonData = commonDataResult.getData();
                            if (commonData == null) {
                                Log.d(TAG, "addToBookShelf: commonData" + commonData);
                                return;
                            }
                            BookDetailBean bookDetailBean = commonData.getData();
                            if (pageFactory.getCurrentContentBean() != null) {
                                pageFactory.addCollection(bookDetailBean);
                                if (isExit) {
                                    ((Activity) mContext).finish();
                                }
//                                DataSupport.getInstance().saveCollection(bookDetailBean, getChapterName(pageFactory.getChapterIndex()), pageFactory.getCurrentContentBean().getChapterId(), pageFactory.getChapterIndex(), 3, 0);
                            }
                        }, throwable -> {
                            DLog.i(TAG, "addToBookShelf getBookDetail error , msg == " + throwable.getMessage());
                            throwable.printStackTrace();
                        });
            }
        }
    }

    /**
     * 上传至书架
     *
     * @param isExit 是否退出阅读器
     */
    private void uploadBookToShelf(boolean isExit) {
        BookshelfService bookshelfService = ApiImp.getInstance().getService(BookshelfService.class);
        bookshelfService.uploadBooks(UserInstance.getToken(), getBookId() + "_1", "app")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(this.bindLifecycle())
                .subscribe(new DisposableObserver<Result>() {

                    @Override
                    public void onNext(Result result) {
                        EventBus.getDefault().post(new LoadBookEvent());
                        if (result.getCode() == 0) {
                            if (isExit) {
                                ((Activity) mContext).finish();
                            } else {
                                quearisAddShelf();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d(TAG, "onNext: 阅读器退出时保存书籍到服务端失败");
                        EventBus.getDefault().post(new LoadBookEvent());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void showLoading(String text) {
        view.showLoading(text);
    }

    public void dismissLoading() {
        view.dismissLoading();
        Log.i("进度条", "dismissLoading: 隐藏了~~");
    }

    public boolean getToNewChapter() {
        return this.toNewChapter;
    }

    //充值
    public void recharge() {
        PayCenterActivity.start(view.getViewContext());
    }

    public void login(LoginFragment loginFragment) {
        loginFragment.show(((BaseActivity) view.getViewContext()).getSupportFragmentManager(), "LoginFragment");
    }

    /**
     * 当前章节是否缓存
     *
     * @return
     */
    public boolean isChapterHasCache(int mChapterIndex) {
        if (mChapterList.size() > 0) {
            return mChapterList.get(mChapterIndex).isCached();
        } else {
            return false;
        }
    }

    /**
     * 保存进度
     */
    public void saveCache() {
//        ACache.get(file).put(getBookId() + "目录", gson.toJson(mChapterList));
        if (!TextUtils.isEmpty(strChapterGSON)) {
            ACache.get(file).put(getBookId() + "目录", strChapterGSON);
        }
    }

    /**
     * 是否从书架进入
     *
     * @return
     */
    public boolean isfromCollect() {
        if (view != null) {
            return view.isfromCollect();
        } else {
            return true;
        }
    }

    /**
     * 是否从激光推送进入
     *
     * @return
     */
    public boolean isfromJush() {
        if (view != null) {
            return view.isfromJush();
        } else {
            return false;
        }
    }


    /**
     * 刷新时间
     *
     * @param bookContentBean
     */
    public void refreshShareTime(BookContentBean bookContentBean) {
        view.refreshShareTime(bookContentBean);
    }

    /**
     * 章节索引发生了变化
     *
     * @param chapterIndex 章节索引
     */
    public void onChapterChanged(int chapterIndex) {
        view.onChapterChanged(chapterIndex);
    }

    public void clearCache() {
//        PreferenceUtil.getInstance(mContext).saveAdValue(getBookId(), 1001);
        try {
            if (cache != null) {
                cache.clear();
            }
        } catch (Exception e) {
            Log.i(TAG, "clearCache: " + e.getMessage());
        }

    }

    /**
     * 登录状态变化
     */
    public void onLoginStatusChanged() {
        file = new File(ReSouApplication.getRSApplication().getApplicationContext().getCacheDir(), getBookId() + (UserInstance.isLogin() ? UserInstance.getToken() : 0));
        cache = ACache.get(file);
    }

    /**
     * 显示限时充值对话框
     */
    public void showLimitedRechargeDialog() {
        DialogManager.showLimitedRechargeDialog(((FragmentActivity) view.getViewContext()).getSupportFragmentManager());
    }

    public void showLoginDialog() {
        DialogManager.showLoginDialog(((FragmentActivity) view.getViewContext()).getSupportFragmentManager());
    }

    public void startToFriendBoostActivity() {
        FriendBoostActivity.start(view.getViewContext());
    }

    /**
     * 显示补贴模式弹框
     */
    public void showSubSidyDialog() {
//        FriendBoostActivity.start(view.getViewContext());
        view.showSubSidyDialog();
    }

    /***
     * VIp开通页面
     */
    public void startVipSubMonthlytActivity() {
        VipCenter.start(view.getViewContext(), false);
    }


    /**
     * 释放对象
     */
    public void recycle() {
        if (mChapterList != null) {
            mChapterList.clear();
        }
        if (downloadSet != null) {
            downloadSet.clear();
        }

    }
}
